package com.ruoyi.web.controller.biz;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

import com.ruoyi.biz.domain.*;
import com.ruoyi.biz.service.*;
import com.ruoyi.common.core.domain.entity.*;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.biz.vo.AdminVo;
import com.ruoyi.biz.vo.EquipmentVo;
import com.ruoyi.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.annotation.Resource;

/**
 * 【请填写功能名称】Controller
 *
 * @author ruoyi
 * @date 2020-11-30
 */
@RestController
@RequestMapping("/system/equipment/info")
//@Api(tags = "设备详情")
public class EquipmentInfoController extends BaseController
{
    private static ExecutorService executorService  = Executors.newFixedThreadPool(10);
    @Autowired
    private IEquipmentInfoService equipmentInfoService;

    @Autowired
    private ISysUserService userService;

    @Resource
    private ISensorInfoService sensorInfoService;
    @Resource
    private IWarnedRecordService warnedRecordService;
    @Resource
    private IMaintainManageService maintainManageService;
    @Resource
    private IRepairRecordService repairRecordService;
    @Resource
    private IChipInfoService chipInfoService;


    @GetMapping("/findName/{equipmentId}")
    public String findName(@PathVariable Long equipmentId){
        EquipmentInfo equipmentInfo = equipmentInfoService.selectEquipmentInfoById(equipmentId);
        return equipmentInfo.getEmergencyContactName();
    }

    /**
     * 用于设备开关机状态更改
     * 设备状态(统一规范:0离线；1开机 2,关机)
     */
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    @GetMapping("/find/all")
    public AjaxResult findAll(){
        return AjaxResult.success(equipmentInfoService.selectEquipmentInfoList(new EquipmentInfo()));
    }



    @ApiOperation("测试设备详情页面接口")
    /**
     * 建议并发提升使用CompletableFuture.runAsync()异步编排优化
     * 要注意传递的查找参数不有能为null，不然直接抛出空指针，建议传递指定参数，自己重写实现方法
     */
    @GetMapping("/equipment/vo/{equipmentId}")
    public EquipmentVo getEquipmentVo(@PathVariable("equipmentId") Long equipmentId){
        EquipmentVo equipmentVo = new EquipmentVo();
        EquipmentInfo equipmentInfo = equipmentInfoService.selectEquipmentInfoById(equipmentId);
        equipmentVo.setEquipmentInfo(equipmentInfo);


        List<ChipInfo> chipInfos = chipInfoService.selectChipByEquipmentId(equipmentId);
        List<SensorInfo> sensorInfos = new ArrayList<>();
        chipInfos.forEach(item->{
            SensorInfo sensorInfo = new SensorInfo();
            sensorInfo.setChipId(item.getChipId());
            List<SensorInfo> sensorInfoList = sensorInfoService.selectSensorInfoList(sensorInfo);
            sensorInfos.addAll(sensorInfoList);
        });
        equipmentVo.setSensorInfos(sensorInfos);


        /**
         * TODO 每个传感器只显示一条最新的告警和最新的预警
         */
        List<WarnedRecord> warnedRecords = new ArrayList<>();
        List<WarnedRecord> warnedRecordList1 = warnedRecordService.findAlarmData(equipmentId);
        List<WarnedRecord> warnedRecordList2 = warnedRecordService.findWarnData(equipmentId);
        warnedRecords.addAll(warnedRecordList1);
        warnedRecords.addAll(warnedRecordList2);
        equipmentVo.setWarnedRecords(warnedRecords);

        MaintainManage maintainManage = new MaintainManage();
        maintainManage.setEquipmentId(equipmentId);
        List<MaintainManage> maintainManages = maintainManageService.selectMaintainManageList(maintainManage);
        equipmentVo.setMaintainManages(maintainManages);

        RepairRecord repairRecord = new RepairRecord();
        repairRecord.setEquipmentId(equipmentId);
        List<RepairRecord> repairRecords = repairRecordService.selectRepairRecordList(repairRecord);
        equipmentVo.setRepairRecords(repairRecords);

        return equipmentVo;
    }

    /**
     * 根据对应传感器名称和报警类型查找对应记录次数
     * @param sensorName
     * @param type
     * @return
     */
    private Integer getSensorInfoNum(String sensorName,Integer type){
        Integer integer = warnedRecordService.selectSensorInfoNumsByName(sensorName,type);
        return integer;
    }


    /**
     * 想提升性能建议使用异步编排
     * @param userName
     * @return
     */
    @ApiOperation("测试管理员详情")
    @GetMapping("/admin/vo/list/{userName}")
    public AdminVo getAdminVo(@PathVariable String userName) throws ExecutionException, InterruptedException {
        AdminVo adminVo = new AdminVo();
        SysUser sysUser = userService.selectUserByUserName(userName);
        adminVo.setSysUser(sysUser);
        EquipmentInfo equipmentInfo = new EquipmentInfo();
        adminVo.setEquipmentInfoList(equipmentInfoService.selectEquipmentInfoList(equipmentInfo));
        return adminVo;
    }

    @GetMapping("/update/sort/{equipmentId}")
    public AjaxResult updateSort(@PathVariable Long equipmentId){
        Integer maxSort = equipmentInfoService.findMaxSort();
        EquipmentInfo equipmentInfo = equipmentInfoService.selectEquipmentInfoById(equipmentId);
        equipmentInfo.setSort(maxSort+1);
        int updateEquipmentInfo = equipmentInfoService.updateEquipmentInfo(equipmentInfo);
        if (updateEquipmentInfo>0){
            return AjaxResult.success("置顶成功");
        }else {
            throw new RuntimeException("置顶失败");
            //return AjaxResult.error("置顶失败");
        }
    }
    /**
     * 查询【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('operate:equipment:info:list')")
    @GetMapping("/list")
    public TableDataInfo list(EquipmentInfo equipmentInfo)
    {
        startPage();
        List<EquipmentInfo> equipmentInfos = equipmentInfoService.selectEquipmentInfoList(equipmentInfo);
        return getDataTable(equipmentInfos);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('operate:equipment:info:export')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(EquipmentInfo equipmentInfo)
    {
        List<EquipmentInfo> list = equipmentInfoService.selectEquipmentInfoList(equipmentInfo);
        ExcelUtil<EquipmentInfo> util = new ExcelUtil<EquipmentInfo>(EquipmentInfo.class);
        return util.exportExcel(list, "info");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
    @PreAuthorize("@ss.hasPermi('operate:equipment:info:query')")
    @GetMapping(value = "/{equipmentId}")
    public AjaxResult getInfo(@PathVariable("equipmentId") Long equipmentId)
    {
        return AjaxResult.success(equipmentInfoService.selectEquipmentInfoById(equipmentId));
    }

    /**
     * 新增【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('operate:equipment:info:add')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EquipmentInfo equipmentInfo)
    {
        return toAjax(equipmentInfoService.insertEquipmentInfo(equipmentInfo));
    }

    /**
     * 修改【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('operate:equipment:info:edit')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改设备信息")
    public AjaxResult edit(@RequestBody EquipmentInfo equipmentInfo)
    {
        logger.debug("打印修改的对象:{}",equipmentInfo);
        return toAjax(equipmentInfoService.updateEquipmentInfo(equipmentInfo));
    }

    /**
     * 删除【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('operate:equipment:info:remove')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
	@DeleteMapping("/{equipmentIds}")
    @ApiOperation("删除设备信息")
    public AjaxResult remove(@PathVariable Long[] equipmentIds)
    {
        return toAjax(equipmentInfoService.deleteEquipmentInfoByIds(equipmentIds));
    }

    /**
     * 设备的启用和停用
     * @param equipmentInfo
     * @return
     */
    @PreAuthorize("@ss.hasPermi('operate:equipment:info:enable:disabled')")
    @Log(title = "启用或停用设备")
    @PostMapping("/startOrStop")
    @ApiOperation("启用或停用设备")
    public AjaxResult startOrStopEquipment(@RequestBody EquipmentInfo equipmentInfo) {
        return toAjax(equipmentInfoService.startOrStopEquipment(equipmentInfo));
    }


    @GetMapping("/isIgnore/{warnedId}")
    @ApiOperation("忽略告警功能")
    public AjaxResult isIgnore(@PathVariable Long warnedId) {
        WarnedRecord warnedRecord = warnedRecordService.selectWarnedRecord(warnedId);
        Integer isIgnoreWarn = warnedRecord.getIsIgnoreWarn();
        logger.info("查询告警的实体:{}",warnedRecord);
        if (isIgnoreWarn==null||isIgnoreWarn==0){
            warnedRecord.setIsIgnoreWarn(1);
        }else {
            warnedRecord.setIsIgnoreWarn(0);
        }
        warnedRecordService.updateWarnedRecord(warnedRecord);
        return AjaxResult.success();
    }

    /*@GetMapping("/listEquipmentOfCurrentUser")
    public AjaxResult listEquipmentOfCurrentUser() {
        return toAjax(equipmentInfoService.selectEquipmentInfoList());
    }*/

}
